package com.example.wnn.utils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.ScanOptions;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

@Component
public class RedisKeyFinder {

    @Autowired
    private StringRedisTemplate redisTemplate;

    public List<String> findKeysWithPrefix(String prefix) {
        List<String> keysWithPrefix = new ArrayList<>();
        // 初始游标为"0"
        String cursor = ScanOptions.ScanOptions.MATCH.getValue() + prefix + "*";
        // 循环迭代直到游标返回"0"
        do {
            // 使用SCAN命令获取带有前缀的key
            ScanOptions scanOptions = ScanOptions.scanOptions().match(cursor + "*").count(1000).build();
            ScanResult<String> scanResult = redisTemplate.execute((connection) ->
                    connection.scan(scanOptions.getCursor(), scanOptions.getOptions()));
            // 获取返回的key集合和新游标
            List<String> keys = scanResult.getResult();
            String newCursor = scanResult.getCursor();

            // 处理返回的keys
            keysWithPrefix.addAll(keys);

            // 更新游标
            cursor = newCursor;
        } while (!cursor.equals("0"));

        return keysWithPrefix;
    }
}